//
//  BHLoginViewController.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/6/10.
//

import UIKit

class BHLoginViewController: BHBaseViewController {
    // 返回
    var loginFail:(() -> Void)?
    
    
    // 布局
    @IBOutlet weak var loginBackBtn: UIButton!
    @IBOutlet weak var title_label: UILabel!
    @IBOutlet weak var welcom_label: UILabel!
    
    @IBOutlet weak var phone_backView: UIView!
    @IBOutlet weak var phoneTextFiled: UITextField!
    
    @IBOutlet weak var code_backView: UIView!
    @IBOutlet weak var codeTextField: UITextField!
    @IBOutlet weak var codeBtn: UIButton!
    
    @IBOutlet weak var loginBtn: UIButton!
    @IBOutlet weak var weixinBtn: UIButton!
    
    @IBOutlet weak var agreeBtn: UIButton!
    
    // 约束
    @IBOutlet weak var closeBtn_to_top: NSLayoutConstraint!
    @IBOutlet weak var agree_to_bottom: NSLayoutConstraint!
    
    
    /**0默认登录页面   1为微信登录的绑定页面*/ 
    var loginType: Int = 0
        
    fileprivate var phone: String = ""
    fileprivate var code: String = ""
    private var timeCount: Int = 60
    private var timer: Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.bh_navigationBar.removeFromSuperview()
        
        self.layoutUI()
        self.configLoginType()
        #if DEBUG
        self.phoneTextFiled.text = "13013115380"
        #else
        
        #endif
        self.phoneTextFiled.delegate = self
        self.codeTextField.delegate = self
        
        self.closeBtn_to_top.constant = 20+UIScreen.stateBarHeight
        self.agree_to_bottom.constant = UIScreen.safeBottomHeight+40
        
        self.resortVC()

    }

    private func resortVC() {
        var temp = self.navigationController?.viewControllers
        if temp!.count > 1 {
            temp?.remove(at: 0)
        }
        self.navigationController?.viewControllers = temp ?? [self]
    }

    private func configLoginType() {
        if self.loginType == 1 {
            self.title_label.text = "请输入手机号码"
            self.welcom_label.text = "根据国家相关法律规定需要进行号码验证"
            self.loginBtn.setTitle("确认", for: .normal)
            self.weixinBtn.isHidden = true
        }
    }
    
    private func layoutUI() {
        self.phone_backView.addLayerCorner(25, 0, .white)
        self.code_backView.addLayerCorner(25, 0, .white)
        self.loginBtn.addLayerCorner(25, 0, .white)
        
        let phonePlace : NSMutableAttributedString = NSMutableAttributedString.init(string: "请输入手机号")
        phonePlace.addFont(.systemFont(ofSize: 14, weight: .medium))
        phonePlace.addAllTextColor(.color_f8f8f8)
        self.phoneTextFiled.attributedPlaceholder = phonePlace
        
        let codePlace : NSMutableAttributedString = NSMutableAttributedString.init(string: "请输入验证码")
        codePlace.addFont(.systemFont(ofSize: 14, weight: .medium))
        codePlace.addAllTextColor(.color_f8f8f8)
        self.codeTextField.attributedPlaceholder = codePlace
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }
    
    
    // 返回
    @IBAction func backAction_login(_ sender: UIButton) {
        self.loginFail?()
    }
    
    // 获取验证码
    @IBAction func getCodeAct(_ sender: UIButton) {
        if self.timeCount != 60 {
            return
        }
        if self.phoneTextFiled.text?.isEmpty == true {
            BHToast.toast(text: "请填写手机号码")
            return
        }
        if self.phoneTextFiled.text?.count != 11 {
            BHToast.toast(text: "请填写正确的手机号码")
            return
        }
        self.view.endEditing(true)
        
        self.getMobileCodeService()
    }
    
    
    
    // 微信登录
    @IBAction func weixinloginAct(_ sender: UIButton) {
        
    }
    
    // 立即登录 || 确认绑定手机号
    @IBAction func loginNowAct(_ sender: UIButton) {
        let canLogion = self.checkInfo()
        if canLogion == true {
            self.mobileAndCodeLoginService()
        }
    }
    
    
    //同意协议的勾选
    @IBAction func agreeAct(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
    }
    
    // 用户使用协议的点击
    @IBAction func lookUseAct(_ sender: UIButton) {
        BHRouter.shared.bh_goWeb(title: "用户协议", linkUrl: String.userAgreementUrl)
    }
    
    // 隐私条款的点击
    @IBAction func privateAct(_ sender: UIButton) {
        BHRouter.shared.bh_goWeb(title: "隐私条款", linkUrl: String.privateAgreementUrl)
    }
    
}

extension BHLoginViewController {
    func checkInfo() -> Bool {
        if self.phoneTextFiled.text?.isEmpty == true {
            BHToast.toast(text: "请填写手机号码")
            return false
        }
        if self.phoneTextFiled.text?.count != 11 {
            BHToast.toast(text: "请填写正确的手机号码")
            return false
        }
        if self.codeTextField.text?.isEmpty == true {
            BHToast.toast(text: "请填写验证码")
            return false
        }
        if self.agreeBtn.isSelected == false {
            BHToast.toast(text: "请先勾选用户协议")
            return false
        }
        return true
    }
}

// 修改状态栏样式
extension BHLoginViewController {
    override var preferredStatusBarStyle: UIStatusBarStyle {
        get {
            return .lightContent
        }
    }
}

// 计时器
extension BHLoginViewController {
    @objc func timeChange() {
        if self.timeCount == 1{
            self.timer!.invalidate()
            timer = nil
            self.codeBtn.setTitle("重新发送", for: .normal)
            self.timeCount = 60
        }else {
            self.timeCount -= 1
            self.codeBtn.setTitle("\(self.timeCount)s", for: .normal)
        }
    }
}

extension BHLoginViewController: UITextFieldDelegate {
    func textFieldDidEndEditing(_ textField: UITextField) {
        if textField == self.phoneTextFiled {
            self.phone = textField.text ?? ""
        }else {
            self.code = textField.text ?? ""
        }
    }
}


// 网络
extension BHLoginViewController {
    func getMobileCodeService() {
        SVProgressHUD.show()
        let manager = BHHTTPClient.init()
        manager.post(url: String.logion_get_mobileCode_url, paramters: ["mobile":self.phoneTextFiled.text!,"smsmode":"0"]) { (success, errorMsg, responseObject)  in
            if success == true {
                BHToast.toast(text: "发送成功")
                #if DEBUG
                let textCode = BHJsonTool.decodeStringFromDic(dic: responseObject, key: "result")
                self.codeTextField.text = textCode
                self.code = textCode
                #else
                
                #endif
                
                if self.timer == nil {
                    self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.timeChange), userInfo: nil, repeats: true)
                    RunLoop.current.add(self.timer!, forMode: .common)
                }
                self.timer!.fire()
            }else {
                let textCode = BHJsonTool.decodeStringFromDic(dic: responseObject, key: "result")
                self.codeTextField.text = textCode
                self.code = textCode
                
                BHToast.toast(text: errorMsg)
            }
            SVProgressHUD.dismiss()
        }
    }
    
    func mobileAndCodeLoginService() {
        SVProgressHUD.show()
        let manager = BHHTTPClient.init()
        manager.post(url: String.logion_mobileCode_logionUrl, paramters: ["mobile":self.phoneTextFiled.text!,"captcha":self.codeTextField.text!,"deviceId":""]) { (success, errorMsg, responseObject)  in
            if success == true {                
//                SVProgressHUD.dismiss()
                // 切换成可登录
                BHMeUserInfoModel.shared.refreshUserInfo(responseObject)
                
                let app = UIApplication.shared.delegate as! AppDelegate
                app.loginIm()

//                BHToast.toast(text: "登录成功")

//                DispatchQueue.main.asyncAfter(deadline: .now()+1) {
//                    // 切换根视图
//                    DispatchQueue.main.async {
//                        UIWindow.keyWindow.rootViewController = BHTabbarController.init();
//                    }
//                }
                          
            }else {
                SVProgressHUD.dismiss()

                BHToast.toast(text: errorMsg)
            }
        }
    }
    
}
